package com.sp.system.user.customer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sp.system.user.core.exception.TokenVerifyException;
import com.sp.system.user.core.utils.enums.PermissionEnum;
import com.sp.system.user.customer.service.IRoleService;
import com.sp.system.user.customer.service.IUserService;
import com.sp.system.user.core.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private IUserService userService;
    @Autowired
    private IRoleService roleService;

    /**定义角色*/
    public  static List<Role> ALL_ROLES = new ArrayList();
    public  static List<Role> ADMIN_ROLES = new ArrayList();
    public  static List<Role> COMMON_ROLES = new ArrayList();
    /**定义权限*/
    public  static List<Menu> ADMIN_MENUS = new ArrayList();
    public  static List<Menu> COMMON_MENUS = new ArrayList();
    static {

    }

    /**
     * @Description:加载用户信息&权限
     * @param: username 用户名
     * @Return: org.springframework.security.core.userdetails.UserDetails
     * @Author: chenanhai
     * @Date: 2019年9月5日
     */

    @Override
    public UserDetails loadUserByUsername(String loginName) throws UsernameNotFoundException {
        User userQuery = new User();
        userQuery.setLoginName(loginName);
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>(userQuery);
        User user = userService.getOne(userQueryWrapper);
//        User user = userService.getUserByLoginName(loginName);

        if ( user != null ){
            UserRole roleUserQuery = new UserRole();
            roleUserQuery.setUserId(user.getId());
            user.setPassword(user.getPassword());
            // 设置 user 角色信息
            try {
                List<Role> roleList = roleService.queryRoleByUserId(roleUserQuery);
                user.setRoles(roleList);
            }catch (Exception e){
                e.printStackTrace();
            }
        } else{
            throw new TokenVerifyException(PermissionEnum.USER_ERROR);
        }

        return new SecurityUserDetails(user);
    }
}
